package org.fastsyncer.connector.sql;

import org.fastsyncer.common.entity.BaseInfo;
import org.fastsyncer.common.entity.DatabaseConfig;
import org.fastsyncer.connector.common.DatabaseConstant;
import org.fastsyncer.connector.framework.AbstractDatabaseConnector;
import org.fastsyncer.connector.util.DatabaseUtil;
import org.springframework.jdbc.core.JdbcTemplate;

public final class SqlMysqlConnector extends AbstractDatabaseConnector {

    private static volatile SqlMysqlConnector instance = null;

    private SqlMysqlConnector() {
    }

    public static SqlMysqlConnector getInstance() {
        if (null == instance) {
            synchronized (SqlMysqlConnector.class) {
                if (null == instance) {
                    instance = new SqlMysqlConnector();
                }
            }
        }
        return instance;
    }
    
    @Override
    public BaseInfo getBaseInfoConnector(DatabaseConfig config, String queryFilter) {
        JdbcTemplate jdbcTemplate = this.getJdbcTemplate(config);
        // SELECT * FROM USER WHERE ID = '123'
        String sql = config.getSql().toUpperCase();
        // 查询元信息
        // SELECT * FROM USER LIMIT 0
        // SELECT * FROM USER WHERE ID = '123' LIMIT 0
        String metaSQL = new StringBuilder().append(sql).append(DatabaseConstant.MYSQL_PAGE_SQL_NULL).toString();

        // 查询连接器基本信息
        BaseInfo connector = DatabaseUtil.getDataSourceConnector(jdbcTemplate, metaSQL, sql);
        // 释放连接
        this.close(jdbcTemplate);
        return connector;
    }

    @Override
    public StringBuilder getPageSQL(DatabaseConfig config, StringBuilder sql) {
        // Mysql 分页查询
        return sql.append(DatabaseConstant.MYSQL_PAGE_SQL);
    }
    
}
